package com.borrow.jiemihua.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by litao
 * 注释:捕获异常信息
 * Created by 2017/12/7.
 */

public class ExceptionHelper implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final boolean DEBUG = true;
    private static final String PATH = Environment
            .getExternalStorageDirectory().getPath() + "/CrashTest/log";
    private static final String FILE_NAME = "crash";
    private static final String FILE_NAME_SUFFIX = ".trace";
    private static ExceptionHelper sInstance = new ExceptionHelper();
    private Thread.UncaughtExceptionHandler mDefauExceptionHandler;
    private Context mContext;

    private ExceptionHelper() {

    }

    public static ExceptionHelper getInstance() {
        return sInstance;
    }

    public void init(Context context) {
        mDefauExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        mContext = context.getApplicationContext();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // TODO Auto-generated method stub
        try {
            // 导出异常信息到sd卡中
            dumpExceptionToSDCard(ex);
            // 上传异常信息到服务器
            uploadExceptionToServer();
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        ex.printStackTrace();
        if (mDefauExceptionHandler != null) {
            mDefauExceptionHandler.uncaughtException(thread, ex);
        } else {
            Process.killProcess(Process.myPid());
        }
    }

    private void dumpExceptionToSDCard(Throwable ex) throws IOException {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {

                return;
            }
        }
        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(current));
        File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(
                    file)));
            pw.println(time);
            dumpPhoneInfo(pw);
            pw.println();
            ex.printStackTrace(pw);
            pw.close();
        } catch (Exception e) {
            // TODO: handle exception

        }

    }

    private void dumpPhoneInfo(PrintWriter pw) throws PackageManager.NameNotFoundException {
        PackageManager pManager = mContext.getPackageManager();
        PackageInfo pInfo = pManager.getPackageInfo(mContext.getPackageName(),
                PackageManager.GET_ACTIVITIES);
        pw.print("APP Version:");
        pw.println(pInfo.versionName);
        pw.print("_");
        pw.println(pInfo.versionCode);
        // Android版本号
        pw.print("OS Version:");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);
        // 手机制造商
        pw.print("Vendor:");
        pw.println(Build.MANUFACTURER);
        // 手机型号
        pw.print("Model:");
        pw.println(Build.MODEL);
        // CPU架构
        pw.print("CPU ABI:");
        pw.println(Build.CPU_ABI);
    }

    private void uploadExceptionToServer() {

    }
}